<!--
 * @description:
 * @author: cuicui
 * @Date: 2023-11-26 12:14:15
 * @LastEditTime: 2024-01-05 11:34:52
 * @LastEditors: cuicui
-->
<template>
  <a-modal
    :title='model ? "编辑用户" : "新建用户"'
    :width='640'
    :visible='visible'
    :confirmLoading='loading'
    @ok='handleSubmit'
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning='loading'>
      <a-form :form='form' v-bind='formLayout'>
        <a-form-item label='id' v-show='false'>
          <a-input v-decorator="['id']" />
        </a-form-item>
        <a-form-item label='账号'>
          <a-input
            autocomplete='new-password'
            v-decorator="['username',
            { rules:  [{ required: true, message: '请输入账号' },
                        { pattern: namePattern,  message: '请输入合法内容(可输入0到50位（中文、字母，数字，下划线，减号)'}], validateTrigger: 'blur'}]" />
        </a-form-item>
        <a-form-item label='用户名'>
          <a-input
            autocomplete='off'
            v-decorator="['nickName',
            { rules:  [{ required: true, message: '请输入用户名' }, { pattern: userNamePattern,  message: '请输入合法用户名(2到16位中文、字母,数字,下划线,减号)'}], validateTrigger: 'blur'}]" />
        </a-form-item>
        <a-form-item label='密码'>
          <a-input type='password'
                   autocomplete='off'
                   v-decorator="['password', {rules: [{ required: true, message: '请输入密码' }, { min: 4,  message: '密码可输入长度未4-10位', max: 10 }], validateTrigger: 'blur'}]" />
        </a-form-item>
        <a-form-item label='联系电话'>
          <a-input
            v-decorator="['phone', {rules: [{ required: true, message: '请输入联系电话' }, { pattern: phonePattern,  message: '请输入合法电话'}], validateTrigger: 'blur'}]" />
        </a-form-item>
        <a-form-item label='用户类型'>
          <a-radio-group name='userType' v-decorator="['userType', { initialValue: model ? model.userType : '2'}]"
                         @change='handleChangeUserType'>
            <a-radio value='2'>
              普通用户
            </a-radio>
            <a-radio value='1'>
              管理员
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label='角色' v-show='roleSelectVisable'>
          <a-select
            v-decorator="['roleIds',  {rules: [{ required: roleSelectVisable, message: '请选择角色' }]}]"
            mode='multiple'
            placeholder='请选择角色'>
            <a-select-option :value='item.id' :key='item.id' v-for='item in roleList'>{{ item.rolename }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label='头像'>
          <a-upload
            name='file'
            list-type='picture-card'
            class='avatar-uploader'
            :show-upload-list='false'
            v-decorator="['avatar',
            {
              valuePropName: 'file',
              getValueFromEvent: normFile,
            }]"
            :action='uploadPath'
            :headers='computedHeaders'
            :before-upload='beforeUpload'
            @change='handleChange'
          >
            <img class='avatar' v-if='imageUrl' :src='baseurl + imageUrl' alt='avatar' />
            <div v-else>
              <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
              <div class='ant-upload-text'>
                上传头像
              </div>
            </div>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { mapState } from 'vuex'
import api, { downloadAvatar } from '@/api/user'
import { findRoleByPage } from '@/api/role'
import { strPattern1 as userNamePattern, phonePattern, agePattern, namePattern } from '@/reges'
import pick from 'lodash.pick'
// 表单字段
const fields = ['id', 'username', 'nickName', 'roleIds', 'phone', 'password', 'age', 'userType', 'gender', 'avatar']
let baseUrl = window.PROJECT_CONFIG.VUE_APP_API_BASE_URL
export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  computed: {
    ...mapState({
      token: state => state.user.token
    }),
    computedHeaders() {
      return {
        [ACCESS_TOKEN]: `Bearer ${this.token}`
      }
    }
  },
  watch: {},
  data() {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      namePattern,
      baseurl: baseUrl,
      uploadPath: baseUrl + api.uploadAvatar,
      userNamePattern,
      phonePattern,
      agePattern,
      roleList: [],
      roleIds: [],
      imageUrl: '',
      id: '',
      uploadLoading: false,
      roleSelectVisable: true,
      form: this.$form.createForm(this)
    }
  },
  created() {
    // 防止表单未注册
    this.getRoleList()
    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      if (this.model) {
        this.roleSelectVisable = this.model.userType !== '1'
      } else {
        this.roleSelectVisable = true
      }
      fields.forEach(v => this.form.getFieldDecorator(v))
      this.model && this.form.setFieldsValue(pick(this.model, fields))
      if (this.form.getFieldValue('avatar')) {
        this.imageUrl = downloadAvatar({
          fileName: this.form.getFieldValue('avatar')
        })
      } else {
        this.imageUrl = ''
      }
      // if (this.model) {
      this.model.roleIds = (this.model && this.model.roleList && this.model.roleList.length) ? this.model.roleList.map(item => item.id) : []
      this.form.setFieldsValue({
        roleIds: this.model.roleIds
      })
      // }
    })
  },
  methods: {
    handleChangeUserType() {
      this.roleSelectVisable = !(this.form.getFieldValue('userType') === '2')
    },
    handleSubmit() {
      this.$emit('ok')
      this.$emit('role-selected', this.form.getFieldValue('roleIds'))
    },
    async getRoleList() {
      const reulst = await findRoleByPage({ pageNo: 1, pageSize: 999, enabled: true })
      this.roleList = reulst.list
    },
    normFile(e) {
      if (Array.isArray(e)) {
        return e
      }
      return e && e.fileList[0] && e.fileList[0].response && e.fileList[0].response.result
    },
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.uploadLoading = true
        return
      }
      if (info.file.status === 'done') {
        this.imageUrl = downloadAvatar({
          fileName: info.file.response.result
        })
        this.uploadLoading = false
        // getBase64(info.file.originFileObj, imageUrl => {
        //   this.uploadLoading = false
        //   this.imageUrl = imageUrl
        // })
      }
    },
    beforeUpload(file) {
      console.log(file, 'file')
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/JEPG'
      if (!isJpgOrPng) {
        this.$message.error('仅支持JPEG格式以及PNG格式文件!')
      }
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('图片大小不得超过 10MB!')
      }
      return isJpgOrPng && isLt2M
    }
  }
}
</script>

<style lang='less'>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.avatar {
  width: 130px;
  height: 130px;
}
</style>
